<template>
  <div class="facility-search-container">
    <div class="map-container" ref="mapContainer">
    </div>

    <!-- Control Panel -->
    <div class="control-panel" id="tools-container">
      <h3 class="panel-title">设施搜索</h3>
      <p class="panel-description">输入设施名称进行搜索</p>

      <!-- 设施类型筛选 -->
      <div class="filter-container">
        <label class="filter-label">设施类型：</label>
        <el-select
          v-model="selectedFacilityType"
          placeholder="选择设施类型"
          class="type-select"
          clearable
        >
          <el-option label="全部" value="" />
          <el-option label="景点" value="景点" />
          <el-option label="餐饮" value="餐饮" />
          <el-option label="驿站" value="驿站" />
        </el-select>
      </div>

      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="输入设施名称搜索"
          class="search-input"
          clearable
        >
          <template #append>
            <el-button @click="searchFacility">
              <el-icon><SearchIcon /></el-icon> 搜索
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 使用 ArcGIS 的 Popup 功能，不再需要自定义对话框 -->

    <!-- Multiple Features Selection Dialog -->
    <el-dialog v-model="selectDialogVisible" title="请选择要素" width="500px" :modal="false">
      <template #header>
        <div class="dialog-header">
          <span>请选择要素</span>
        </div>
      </template>
      <div class="feature-selector">
        <el-table :data="selectedFeatures" style="width: 100%" class="feature-table">
          <el-table-column prop="attributes.facilityname || attributes.RoadName" label="名称">
            <template #default="{ row }">
              {{ row.attributes.facilityname || row.attributes.RoadName || '未命名要素' }}
            </template>
          </el-table-column>
          <el-table-column prop="layer.id" label="要素类型">
            <template #default="{ row }">
              {{ getLayerType(row.layer.id) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ $index }">
              <el-button type="primary" size="small" @click="handleSelect($index)" class="select-btn">
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- Search Results Panel -->
    <el-card
      v-if="showSearchResults"
      class="search-results-panel"
      :body-style="{ padding: '10px' }"
    >
      <template #header>
        <div class="results-header">
          <span>设施搜索结果</span>
          <div>
            <el-button
              type="primary"
              size="small"
              @click="showSelectedSearchResults"
              :disabled="selectedSearchResults.length === 0"
            >
              查看选中
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="showSearchResults = false"
              class="close-button"
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>
      </template>

      <el-scrollbar height="300px">
        <el-checkbox-group v-model="selectedSearchResults">
          <div v-for="(feature, index) in searchResults" :key="index" class="result-item">
            <el-checkbox :label="index">
              {{ feature.attributes.facilityname || '未命名设施' }}
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </el-scrollbar>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search as SearchIcon, Close } from '@element-plus/icons-vue'
import Graphic from '@arcgis/core/Graphic'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Query from '@arcgis/core/rest/support/Query.js'
import Handles from '@arcgis/core/core/Handles.js'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol'
import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer'
import PopupTemplate from '@arcgis/core/PopupTemplate'
import FieldInfo from '@arcgis/core/popup/FieldInfo'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import {
  facilityPointSymbol,
  scenicPointSymbol,
  viewScenicSpotSymbol,
  serviceSymbol,
  monitorSymbol,
  trafficSymbol,
  greenSymbol
} from '@/utils/facilityIcons'

const mapContainer = ref<HTMLDivElement>()

// 使用统一的设施图标符号（已从 facilityIcons.ts 导入）

// Create road symbol
const roadSymbol = new SimpleLineSymbol({
  color: [0, 122, 194, 0.8],
  width: 4,
  style: 'solid',
  cap: 'round',
  join: 'round',
})

// Create facility layer
const facilityLayer = new FeatureLayer({
  url: 'https://services.arcgis.com/cxicHGWOCJwYXasp/arcgis/rest/services/Facility/FeatureServer/0',
  outFields: ['*'],
  renderer: {
    type: 'unique-value',
    field: 'facilitytype',
    defaultSymbol: facilityPointSymbol,
    uniqueValueInfos: [
      {
        value: '驿站',
        symbol: scenicPointSymbol,
      },
      {
        value: '景点',
        symbol: viewScenicSpotSymbol,
      },
      {
        value: '餐饮',
        symbol: facilityPointSymbol,
      },
    ],
  } as never,
  // 添加弹出窗口模板
  popupTemplate: new PopupTemplate({
    title: "{facilityname}",
    content: [
      {
        type: "fields",
        fieldInfos: [
          new FieldInfo({
            fieldName: "facilityname",
            label: "设施名称"
          }),
          new FieldInfo({
            fieldName: "facilitytype",
            label: "设施类型"
          }),
          new FieldInfo({
            fieldName: "OtherJson",
            label: "详细信息"
          }),
        ]
      }
    ]
  })
})

// Create road layer
const roadLayer = new FeatureLayer({
  url: 'https://www.geosceneonline.cn/server/rest/services/Hosted/S103/FeatureServer/0',
  outFields: ['*'],
  renderer: {
    type: 'simple',
    symbol: roadSymbol,
  } as never,
  // 添加弹出窗口模板
  popupTemplate: new PopupTemplate({
    title: "{RoadName}",
    content: [
      {
        type: "fields",
        fieldInfos: [
          new FieldInfo({
            fieldName: "RoadName",
            label: "道路名称"
          }),
          new FieldInfo({
            fieldName: "RoadType",
            label: "道路类型"
          }),
          new FieldInfo({
            fieldName: "RoadLength",
            label: "道路长度"
          })
        ]
      }
    ]
  })
})

// Create sketch layer for drawing
const sketchLayer = new GraphicsLayer({
  title: '绘图图层',
})

// Create map
const map = new Map({
  basemap: {
    baseLayers: [gaodeLayer],
  },
})

// Add layers to map
map.add(facilityLayer)
map.add(roadLayer)
map.add(sketchLayer)

// Create map view
const view = new MapView({
  map: map,
  center: [117.14435714426122, 36.29746937366678],
  zoom: 10,
})

// State variables
const selectDialogVisible = ref(false)
const selectedFeatures = ref<any[]>([])
const selectedFeatureIndex = ref(0)
const highlightHandle: Handles = new Handles() // 高亮显示句柄
let selectFeatureLayer: FeatureLayer | null = null
let selectGraphic: Graphic | null = null
let allSelectGraphics: Graphic[] = []

// Search related state
const searchKeyword = ref('')
const selectedFacilityType = ref('')
let searchResults: Graphic[] | null = null
const showSearchResults = ref(false)
const selectedSearchResults = ref<number[]>([])

// Search facility by name and type
async function searchFacility() {
  if (!searchKeyword.value.trim() && !selectedFacilityType.value) {
    ElMessage.warning('请输入搜索关键词或选择设施类型')
    return
  }

  try {
    // Build query conditions
    let whereClause = '1=1' // Base condition

    // Add name filter if keyword is provided
    if (searchKeyword.value.trim()) {
      whereClause += ` AND facilityname LIKE '%${searchKeyword.value}%'`
    }

    // Add type filter if type is selected
    if (selectedFacilityType.value) {
      whereClause += ` AND facilitytype = '${selectedFacilityType.value}'`
    }

    // Create query with combined conditions
    const query = new Query({
      where: whereClause,
      outFields: ['*'],
      returnGeometry: true,
    })

    const result = await facilityLayer.queryFeatures(query)
    searchResults = result.features

    if (searchResults.length === 0) {
      ElMessage.info('未找到匹配的设施')
    } else {
      showSearchResults.value = true
      selectedSearchResults.value = [] // Clear selected items
      ElMessage.success(`找到 ${searchResults.length} 个匹配的设施`)
    }
  } catch (error) {
    console.error('搜索设施失败:', error)
    ElMessage.error('搜索设施失败')
  }
}

// Show selected search results
function showSelectedSearchResults() {
  if (selectedSearchResults.value.length === 0) {
    ElMessage.warning('请至少选择一个设施')
    return
  }

  // Get selected graphics
  const selectedGraphics = selectedSearchResults.value.map((index) => searchResults![index])

  // If only one result, show attributes directly
  if (selectedGraphics.length === 1) {
    selectFeatureLayer = facilityLayer
    selectGraphic = selectedGraphics[0]
    showAttributes(selectedGraphics[0])
  } else {
    // Multiple results show selection dialog
    selectedFeatures.value = selectedGraphics.map((g) => ({
      attributes: structuredClone(g.attributes),
      geometry: structuredClone(g.geometry),
      layer: { id: facilityLayer.id },
    }))
    allSelectGraphics = selectedGraphics
    selectedFeatureIndex.value = 0
    selectDialogVisible.value = true
  }

  // Close search results panel
  showSearchResults.value = false
}

// Get layer type based on layer ID
function getLayerType(id: string) {
  if (id === facilityLayer.id) {
    return '设施'
  } else if (id === roadLayer.id) {
    return '道路'
  }
  return '未知类型'
}

// Handle feature selection
function handleSelect(index: number) {
  selectedFeatureIndex.value = index
  confirmSelection()
}

// Confirm feature selection
function confirmSelection() {
  selectFeatureLayer = facilityLayer
  selectGraphic = allSelectGraphics[selectedFeatureIndex.value]
  showAttributes(selectedFeatures.value[selectedFeatureIndex.value] as __esri.Graphic)
  selectDialogVisible.value = false
}

// Initialize map view in onMounted
onMounted(() => {
  // Initialize map view container
  view.container = mapContainer.value as HTMLDivElement
  view.ui.add('tools-container', 'top-right')
})

// Show feature attributes
function showAttributes(feature: __esri.Graphic) {
  // Clear previous highlight
  highlightHandle.removeAll()

  // Highlight selected feature
  if (selectFeatureLayer && selectGraphic) {
    // Create a highlight graphic
    const highlightSymbol = selectFeatureLayer.id === facilityLayer.id
      ? {
          type: 'simple-marker',
          style: 'circle',
          color: [255, 255, 0, 0.8],
          size: '16px',
          outline: {
            color: [255, 255, 0, 0.8],
            width: 3
          }
        }
      : {
          type: 'simple-line',
          color: [255, 255, 0, 0.8],
          width: 6
        };

    const highlightGraphic = new Graphic({
      geometry: selectGraphic.geometry,
      symbol: highlightSymbol as any
    });

    // Add highlight graphic to view
    view.graphics.add(highlightGraphic);

    // Store the highlight handle for later removal
    highlightHandle.add({
      remove: () => {
        view.graphics.remove(highlightGraphic);
      }
    });
  }

  // Zoom to the feature
  view.goTo({
    target: feature.geometry,
    zoom: 15
  }).then(() => {
    // 显示弹出窗口
    view.popup?.open({
      features: [feature]
    });
  });
}

// 不再需要 getLabel 函数，因为我们使用了 PopupTemplate 的 fieldInfos
</script>

<style scoped>
.facility-search-container {
  height: 100%;
  width: 100%;
  position: relative;
}

.map-container {
  height: 100%;
  width: 100%;
  position: relative;
}

/* Control panel styles */
.control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
  background: rgba(24, 44, 78, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.15);
  transition: all 0.3s ease;
  color: #fff;
  width: 280px;
}

.panel-title {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 18px;
  color: #fff;
}

.panel-description {
  margin-bottom: 15px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.filter-container {
  margin-bottom: 15px;
}

.filter-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.type-select {
  width: 100%;
}

.search-container {
  margin-bottom: 10px;
}

.search-input {
  width: 100%;
}

/* Dialog styles */
:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.3);
  border: none;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #1976D2, #42A5F5);
  color: white;
  padding: 15px;
  border-bottom: none;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  font-weight: 600;
  color: white;
}

/* 移除不再需要的样式 */

.feature-selector {
  max-height: 300px;
  overflow-y: auto;
}

.feature-table {
  border-radius: 8px;
  overflow: hidden;
}

.select-btn {
  padding: 4px 12px;
}

/* Panel styles */
.search-results-panel {
  position: fixed;
  left: 20px;
  top: 20px;
  width: 320px;
  z-index: 1500;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  border: none;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  font-weight: 600;
  color: white;
}

:deep(.el-card__header) {
  background: linear-gradient(135deg, #1976D2, #42A5F5);
  color: white;
  padding: 12px 15px;
  border-bottom: none;
}

.close-button {
  padding: 5px 12px;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.result-item {
  padding: 8px;
  border-bottom: 1px solid #ebeef5;
}

.result-item:last-child {
  border-bottom: none;
}
</style>
